//
//  FeaturedViewContoller.m
//  CoMeT
//
//  Created by Gang on 6/12/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "FeaturedViewContoller.h"
#import "DefaultTableViewCell.h"
#import "ColloquiumViewController.h"
#import "NetUtil.h"
#import "TBXML.h"

@implementation UINavigationBar (UINavigationBarCustomDraw)
- (void)drawRect:(CGRect)rect {
    
    UIColor *naviColor = [[UIColor alloc] initWithRed:142 green:180 blue:227 alpha:1];
    [self setTintColor:naviColor];
    [naviColor release];
    
    UIImage *image = [UIImage imageNamed: @"logo.png"];
    [image drawInRect:CGRectMake(120, 5, 80 , 30)];
    
    
}
@end


@implementation FeaturedViewContoller
@synthesize mytableView;
@synthesize segmentedControl;
@synthesize talks;

@synthesize titleText;
@synthesize detailText;
@synthesize viewCount;
@synthesize bookmarkCount;
@synthesize footerView;

@synthesize sections;
@synthesize sortedSections;
@synthesize refreshBtn;


-(void) refreshTalks:(id)sender{
    if ([NetUtil checkNetworkStatus:nil] == 3) {
        [self parseData];
    }else{
        
        UIAlertView *networkAlert = [[UIAlertView alloc] initWithTitle:@"Network Error" message:@"Cann't Connect To Server" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [networkAlert show];
        [networkAlert release];
    }
    
    [self.mytableView reloadData]; 

    
}


-(void) parseData{
    
    
    
    NSString *urlAddress = [NSString stringWithFormat:@"http://halley.exp.sis.pitt.edu/comet/utils/loadTalkXML.jsp?week=%i", weekcount];
    
    NSURL *url=[[NSURL alloc] initWithString:urlAddress];
    
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
    [url release];
    
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:[urlAddress dataUsingEncoding:NSASCIIStringEncoding]];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    
    
    NSURLResponse *response;
    NSError *error;
    NSData *aData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    NSString *serverOutputSch = [[NSString alloc] initWithData:aData encoding: NSASCIIStringEncoding];
    //NSLog(@"%@", serverOutputSch);
    
    
    TBXML *tbxml = [[TBXML alloc] initWithXMLString:serverOutputSch];
    [serverOutputSch release];
    TBXMLElement *root = tbxml.rootXMLElement;
    
    // if root element is valid
    if (root) {
        
        NSMutableArray *items =[[NSMutableArray alloc] init];
        //
        // Data Formater
        //
        NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
        [dateformatter setDateFormat:@"MMM dd, yyyy"];
        
        if(root->firstChild){
            TBXMLElement *currentItem = root->firstChild;
            
            do {
                NSMutableDictionary *item = [[NSMutableDictionary alloc] init];
                self.titleText= [[NSMutableString alloc] init];
                self.detailText= [[NSMutableString alloc] init];
                self.viewCount = [[NSMutableString alloc] init];
                self.bookmarkCount = [[NSMutableString alloc] init];
                
                [self.titleText appendString:[TBXML textForElement:[TBXML childElementNamed:@"title" parentElement:currentItem]]];
                
                [self.detailText appendString:[TBXML textForElement:[TBXML childElementNamed:@"speaker" parentElement:currentItem]]];
                
                if ([TBXML childElementNamed:@"affiliation" parentElement:currentItem] != nil) {
                    [self.detailText appendFormat:@", %@",[TBXML textForElement:[TBXML childElementNamed:@"affiliation" parentElement:currentItem]]];
                }
                
                
                
                
                if ([TBXML childElementNamed:@"viewno" parentElement:currentItem] != nil) {
                    [self.viewCount appendString:[TBXML textForElement:[TBXML childElementNamed:@"viewno" parentElement:currentItem]]];
                }else
                {
                    [self.viewCount appendString:@"0"];
                    
                }
                
                
                if ([TBXML childElementNamed:@"bookmarkno" parentElement:currentItem] != nil) {
                    [self.bookmarkCount appendString:[TBXML textForElement:[TBXML childElementNamed:@"bookmarkno" parentElement:currentItem]]];
                }else
                {
                    [self.bookmarkCount appendString:@"0"];
                }
                
                
                //[self.viewCount appendString:[TBXML textForElement:[TBXML childElementNamed:@"sessionName" parentElement:currentItem]]];
                //[self.bookmarkCount appendString:[TBXML textForElement:[TBXML childElementNamed:@"sessionName" parentElement:currentItem]]];
                

                [item setObject:[TBXML valueOfAttributeNamed:@"id" forElement:currentItem] forKey:@"id"];
                [item setObject:self.titleText forKey:@"title"];
                [item setObject:self.viewCount forKey:@"viewCount"];
                [item setObject:self.bookmarkCount forKey:@"bookmarkCount"];
                [item setObject:self.detailText forKey:@"detail"];
                
                
                
                [item setObject:[TBXML textForElement:[TBXML childElementNamed:@"location" parentElement:currentItem]] forKey:@"location"];
                NSArray *dateSet = [[TBXML textForElement:[TBXML childElementNamed:@"date" parentElement:currentItem]] componentsSeparatedByString:@","];
                
                NSString *dateString = [NSString stringWithFormat:@"%@, 2011",[dateSet objectAtIndex:1]];
                [item setObject: dateString forKey:@"date"];
                
                [item setObject:[TBXML textForElement:[TBXML childElementNamed:@"begintime" parentElement:currentItem]] forKey:@"begintime"];
                
                [item setObject:[TBXML textForElement:[TBXML childElementNamed:@"endtime" parentElement:currentItem]] forKey:@"endtime"];
                
                [item setObject:[TBXML textForElement:[TBXML childElementNamed:@"owner" parentElement:currentItem]] forKey:@"owner"];
                
                [items addObject:item];
                [item release];
                
            } while ((currentItem = currentItem->nextSibling));
            

            
            self.talks = items;
            //NSMutableDictionary *tempSections = [NSMutableDictionary alloc] init]
            
            self.sections = [[NSMutableDictionary alloc] init];
            BOOL found;
            
            // Loop through the books and create our keys
            for (NSDictionary *talk in self.talks)
            {
                NSString *c = [talk objectForKey:@"date"];
                
                found = NO;
                
                for (NSString *str in [self.sections allKeys])
                {
                    if ([str isEqualToString:c])
                    {
                        found = YES;
                    }
                }
                
                if (!found)
                {
                    [self.sections setValue:[[NSMutableArray alloc] init] forKey:c];
                }
            }
            
            //loop again to sort talks in each section
            for (NSDictionary *talk in self.talks)
            {
                [[self.sections objectForKey:[talk objectForKey:@"date"]] addObject:talk];
            }
            
            //NSLog(@"section keys %i", [[self.sections allKeys]count]);
            NSSortDescriptor *timeSort = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:YES comparator:^NSComparisonResult(id obj1, id obj2) {
                return [[dateformatter dateFromString:obj1] compare:[dateformatter dateFromString:obj1]]; 
            } ];
            for (NSString *key in [self.sections allKeys])
            {
                [[self.sections objectForKey:key] sortUsingDescriptors:[NSArray arrayWithObject:timeSort]];
            }
            [timeSort release];
            if (self.sortedSections == nil) {
                self.sortedSections = [[NSArray alloc] init];
            }
            
            
            // sort sections 
            self.sortedSections = [[self.sections allKeys] sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {

                return [[dateformatter dateFromString:obj1] compare:[dateformatter dateFromString:obj1]];
                
            }];
            
        }
        [items release];
        [dateformatter release];
    }
    [tbxml release];
  
}





// table delegation

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [self.sortedSections count];
}


// Customize the number of rows in the table view.

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    if ([talks count]==0) {
        return 1;
    }else{
        
        if (section == [self.sections count]-1) {
            return [[self.sections objectForKey:[self.sortedSections objectAtIndex:section]] count]+1; 
        }else{
            return [[self.sections objectForKey:[self.sortedSections objectAtIndex:section]] count];
        }
        
    }

}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"MMM dd, yyyy"];
    NSDateFormatter *dateformatter1 = [[NSDateFormatter alloc] init];
    
    [dateformatter1 setDateFormat:@"EEEE,MMM dd,yyy"];
    NSDate *date = [dateformatter dateFromString:[self.sortedSections objectAtIndex:section]];
    NSString *result = [dateformatter1 stringFromDate:date];
    [dateformatter release];
    [dateformatter1 release];
    
    return result; 
    
}


// Customize the appearance of table view cells.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"DefaultTalbeViewCell";

    DefaultTableViewCell *cell = (DefaultTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {
        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"DefaultTableViewCell" owner:nil options:nil];
        
        for(id currentObject in topLevelObjects)
        {
            if([currentObject isKindOfClass:[DefaultTableViewCell class]])
            {
                cell = (DefaultTableViewCell *)currentObject;
                break;
            }
        }
        
    }

    
    if ([self.talks count] == 0) {
        
        UITableViewCell *cell = [[[UITableViewCell alloc] init] autorelease]; 
		cell.selectionStyle = UITableViewCellSelectionStyleNone;
		return cell;
		
	} else if (indexPath.section == [self.sortedSections count]-1 && indexPath.row == [[self.sections objectForKey:[self.sortedSections objectAtIndex:indexPath.section]] count]){ // Special Case 2		
		
		UITableViewCell *loadingCell = [[[UITableViewCell alloc]init] autorelease];
		loadingCell.textLabel.text= @"Load More";
        loadingCell.textLabel.textAlignment = UITextAlignmentCenter;
        return loadingCell;

        
	}
    
    
    // Set up the cell...  
    
    
    cell.titleText.text = [[[self.sections objectForKey:[self.sortedSections objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row] objectForKey:@"title"];
    cell.author.text = [[[self.sections objectForKey:[self.sortedSections objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row] objectForKey:@"detail"];
    
    
    cell.viewCount.text = [NSString stringWithFormat:@"%@ view", [[[self.sections objectForKey:[self.sortedSections objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row] objectForKey:@"viewCount"]];
    
    if ( [cell.viewCount.text isEqualToString:@"0"]) {
        [cell.eyeIcon setHidden:YES];
    }
    
    cell.bookmarkCount.text = [NSString stringWithFormat:@"%@ bookmark", [[[self.sections objectForKey:[self.sortedSections objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row] objectForKey:@"bookmarkCount"]];
    
    if ([cell.bookmarkCount.text isEqualToString:@"0"]) {
        [cell.starIcon setHidden:YES];
    }
    return cell;

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == [self.sortedSections count]-1 && indexPath.row == [[self.sections objectForKey:[self.sortedSections objectAtIndex:indexPath.section]] count]){
        return 40;
    }
    
    return 100;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // open a alert with an OK and cancel button
    if (indexPath.section == [self.sortedSections count]-1 && indexPath.row == [[self.sections objectForKey:[self.sortedSections objectAtIndex:indexPath.section]] count]){
        weekcount ++;
        [self parseData];
        NSLog(@"week %i", weekcount);
        [self.mytableView reloadData];
        return;
    }
    
    
    ColloquiumViewController *colloquiumView = [[ColloquiumViewController alloc]init];
    
    colloquiumView.talk = [[self.sections objectForKey:[self.sortedSections objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
    
    
    
    [self.navigationController pushViewController:colloquiumView animated:YES];
    
    [colloquiumView release];

}


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{

    [self.titleText release];
    [self.detailText release];
    [self.viewCount release];
    [self.bookmarkCount release];
    [self.talks release];
    [self.sections release];
    [self.sortedSections release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.segmentedControl.selectedSegmentIndex = 0;
    
    self.segmentedControl.hidden = YES;
    talks = [[NSMutableArray alloc] init];
    weekcount = 1;
    if ([NetUtil checkNetworkStatus:nil] == 3) {
        [self parseData];
    }else{
        
        UIAlertView *networkAlert = [[UIAlertView alloc] initWithTitle:@"Network Error" message:@"Cann't Connect To Server" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [networkAlert show];
        [networkAlert release];
    }
    
    //[self.mytableView reloadData];

}


-(void)viewWillAppear:(BOOL)animated{

    
}


- (IBAction) action:(id)sender{
    //UISegmentedControl *segmentedControl = (UISegmentedControl *) sender;
    
    //[segmentedControl release];
    NSLog(@"SegmentedControl %@ selected", segmentedControl.selectedSegmentIndex);
    //[self.mytableView reloadData];
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}




@end
